package com.kurumi.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.kurumi.config.MyConfig;
import com.kurumi.pojo.MedicalRecord;
import com.kurumi.pojo.RespondResult;
import com.kurumi.pojo.ScanImage;
import com.kurumi.pojo.upload.UploadThirdScan;
import com.kurumi.query.UploadScanQuery;
import com.kurumi.service.MedicalRecordService;
import com.kurumi.service.UploadThirdScanService;
import com.kurumi.util.GuidUtil;

@Controller
@RequestMapping("/upload_scan")
public class UploadScanController {

	@Autowired
	private MyConfig myConfig;
	
	@Autowired
	private UploadThirdScanService uploadThirdScanService;
	
	@Autowired
	private MedicalRecordService medicalRecordService;
	
	/**
	 * 第三方扫描文件上传
	 * @param file
	 * @param request
	 * @return
	 */
	@PostMapping(value = "/upload_third_scan")
	public String uploadThirdScan(@RequestParam("files")MultipartFile[] files,HttpServletRequest request) {
		int count = 0;
		try {
			Subject subject=SecurityUtils.getSubject();
			Session session = subject.getSession();
			Map<String, Object> currentUser = (Map<String, Object>)session.getAttribute("currentUser");
			String userCode =(String)currentUser.get("user_code");
			String userName =(String)currentUser.get("user_name");
			System.out.println("文件数量:"+files.length);
			List<UploadThirdScan> uploadThirdScans = new ArrayList<UploadThirdScan>();
			Map<String, UploadThirdScan> thirdUploadScanMap = new HashMap<String, UploadThirdScan>();
			if(files!=null && files.length>0){
				for (MultipartFile multipartFile : files) {
					//文件原名称
					String originalFilename=multipartFile.getOriginalFilename();
					String[] splits = originalFilename.split("/");
					//文件名称
					String fileName =splits[splits.length-1];
					//文件夹名字
					String folderName=splits[splits.length-2];
					UploadThirdScan uploadThirdScan = thirdUploadScanMap.get(folderName);
					if(uploadThirdScan == null){
						uploadThirdScan = new UploadThirdScan();
						uploadThirdScan.setUploadDateTime(new Date());
						uploadThirdScan.setUploadUserCode(userCode);
						uploadThirdScan.setUploadUserName(userName);
						uploadThirdScan.setUploadFolderName(folderName);
						thirdUploadScanMap.put(folderName, uploadThirdScan);
						uploadThirdScans.add(uploadThirdScan);
					}
					//文件流Hash（100位）
					String hashStr = new StringBuffer(GuidUtil.get36SystemHash(new String(multipartFile.getBytes()))).reverse().toString();
					//获取文件后缀名
					String fileSuffixes = originalFilename.substring(originalFilename.lastIndexOf(".")+1);
					long fileSize = multipartFile.getSize();
					String fileSizeHashStr = GuidUtil.get36SystemHash(fileSize);
					
					//文件Hash
					String fileHash = new StringBuffer(hashStr).append(fileSizeHashStr).toString();
					/*ScanFile scanFile = new ScanFile();*/
					ScanImage scanImage = new ScanImage();
					scanImage.setFileHash(fileHash);
					String localPath = GuidUtil.getLocalPath(hashStr);
					String remoteUrl = GuidUtil.getRemoteUrl(hashStr);
					//文件摘要后92位  文件摘要hash值 + 文件大小的5位hash值  
					 hashStr = hashStr.substring(8)+fileSizeHashStr.substring(0, 5);
					
					 
					//文件保存路径
					String filePath = myConfig.getImageRecourcePath() + localPath;
					File destFile = new File(filePath,hashStr+"."+fileSuffixes);
					if(!destFile.exists()){
						File destDir = new File(filePath);
						if(!destDir.exists()){
							destDir.mkdirs();
						}
						multipartFile.transferTo(destFile);
					}
					scanImage.setOriginalFileName(fileName);
					scanImage.setFileName(hashStr+"."+fileSuffixes);
					scanImage.setFileType(fileSuffixes);
					scanImage.setCreateUserId(userCode);
					scanImage.setCreateUserName(userName);
					
					
					
					uploadThirdScan.getScanImages().add(scanImage);
				
				}
			}
			count = uploadThirdScanService.uploadThirdScan(uploadThirdScans);
		} catch (Exception e) {
			e.printStackTrace();
			count = -1;
		}
		return "redirect:/medical_record_scan/third_scan_upload_page?errorCode="+count;
		
	}
	
	@GetMapping("/ajax_upload_third_scan_query")
	@ResponseBody
	public RespondResult ajaxUploadThirdScanQuery(UploadScanQuery params){
		RespondResult respondResult = null;
		
		try{
			List<Map<String,Object>> records = new ArrayList<Map<String,Object>>();
			int count = 0;
			if(!params.isEmpty()){
				records = uploadThirdScanService.getUploadThirdScanByQuery(params);
				count= uploadThirdScanService.getUploadThirdScanCountByQuery(params);
			}
			
			params.setTotalCounts(count);
			params.setDatas(records);
			respondResult = new RespondResult(true, RespondResult.successCode, null, params);
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), params);
		}
		
		return respondResult;
	}
	
	@GetMapping("/ajax_check_upload_relevance")
	@ResponseBody
	public RespondResult ajaxCheckUploadRelevance(String mrId,Integer visitNumber){
		RespondResult respondResult = null;
		
		try{
			List<String> records = new ArrayList<String>();
			records = medicalRecordService.getVisitGuidByMrIdAndVisitNumber(mrId,visitNumber);
			respondResult = new RespondResult(true, RespondResult.successCode, null, records.size());
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), null);
		}
		
		return respondResult;
	}
	
	
	@PostMapping("/ajax_add_medical_record_relevance")
	@ResponseBody
	public RespondResult ajaxAddMedicalRecordRelevance(MedicalRecord medicalRecord,Integer uploadScanId){
		RespondResult respondResult = null;
		
		try{
			int count = medicalRecordService.checkMeditalRecordUniq(medicalRecord.getOnlyId(), medicalRecord.getMrId(), medicalRecord.getVisitNumber());
			if(count > 0){
				return new RespondResult(true, RespondResult.repeatCode, null, count);
			}
			count = uploadThirdScanService.addMedicalRecordRelevance(medicalRecord,uploadScanId);
			if(count == 1){
				respondResult = new RespondResult(true, RespondResult.successCode, null, medicalRecord.getVisitGuid());
			}else{
				respondResult = new RespondResult(true, RespondResult.errorCode, "非预期结果", null);
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
			e.printStackTrace();
		}
		
		return respondResult;
	}
	
	@PostMapping("/ajax_medical_record_relevance")
	@ResponseBody
	public RespondResult ajaxMedicalRecordRelevance(String mrId,Integer visitNumber,Integer uploadScanId){
		RespondResult respondResult = null;
		
		try{
			int count = uploadThirdScanService.medicalRecordRelevance(mrId,visitNumber,uploadScanId);
			if(count == 1){
				List<String> visitGuids = medicalRecordService.getVisitGuidByMrIdAndVisitNumber(mrId, visitNumber);
				respondResult = new RespondResult(true, RespondResult.successCode, null, visitGuids.get(0));
			}else{
				respondResult = new RespondResult(true, RespondResult.errorCode, "非预期结果", null);
			}
			
		}catch (Exception e) {
			// TODO: handle exception
			respondResult = new RespondResult(false, RespondResult.errorCode, e.getMessage(), "");
		}
		
		return respondResult;
	}
	
}
